//
//  JoinViewController.m
//  cm
//
//  Created by suyibaishan on 2017/11/6.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "JoinViewController.h"
#import "AuditViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "NXSignatureController.h"

#define kUrlScheme  @"ali01010106" // URL Scheme，支付宝、微信支付和测试模式需要。

@interface JoinViewController () <UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    NSArray *dataSource;
    UIView *headView;
    UIButton *confirmBtn;
    UIAlertController *mAlert;
}
@end

@implementation JoinViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createJoinView];
}

-(void)createJoinView
{
    self.titleLabel.text = @"加入VIP";
    self.backButton.hidden = NO;
    
    [self createHeadView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.baseBarHeight, kScreenWidth, kScreenHeight - self.baseBarHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
     _tableView.tableHeaderView = headView;
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    _tableView.tableFooterView = footView;
    
    confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    confirmBtn.layer.cornerRadius = 20;
    confirmBtn.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:[NSString stringWithFormat:@"确认支付¥10000"] forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [confirmBtn addTarget:self action:@selector(confirmBtnHandler) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:confirmBtn];
    confirmBtn.sd_layout
    .leftSpaceToView(footView, 50)
    .topSpaceToView(footView, 40)
    .widthIs(kScreenWidth - 100)
    .heightIs(40);
    
    dataSource = [NSMutableArray array];
}

-(void)createHeadView
{
    headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    headView.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:headView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-100)/2, 25, 100, 100)];
//    imageView.contentMode = UIViewContentModeScaleAspectFill;
//    imageView.clipsToBounds = YES;
    imageView.image = [UIImage imageNamed:@"cm_car"];
    [headView addSubview:imageView];
    
    UILabel *priceLabel = [[UILabel alloc] init];
    priceLabel.textAlignment = NSTextAlignmentCenter;
    priceLabel.font = [UIFont systemFontOfSize:19];
    priceLabel.textColor = [UIColor blackColor];
    [headView addSubview:priceLabel];
    priceLabel.sd_layout
    .topSpaceToView(imageView, 10)
    .leftSpaceToView(headView, 15)
    .widthIs(kScreenWidth - 30)
    .heightIs(20);
    priceLabel.text = @"10000.00";
    
    UILabel *approveLabel = [[UILabel alloc] init];
    approveLabel.textAlignment = NSTextAlignmentCenter;
    approveLabel.text = @"开通车盟VIP";
    approveLabel.font = [UIFont systemFontOfSize:13];
    approveLabel.textColor = [UIColor blackColor];
    [headView addSubview:approveLabel];
    approveLabel.sd_layout
    .topSpaceToView(priceLabel, 0)
    .leftSpaceToView(headView, 50)
    .widthIs(kScreenWidth - 100)
    .heightIs(20);
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    [headView addSubview:view];
    view.sd_layout
    .bottomSpaceToView(headView, 0)
    .leftSpaceToView(headView, 0)
    .widthIs(kScreenWidth)
    .heightIs(5);
}

-(void)confirmBtnHandler
{
    [self showAlertWait];
    [[ToolNet sharedManager] payCheck:self.userCode payMethod:@"alipay" url:MPayCheck completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        [self hideAlert];
        if ([responseJson[@"code"] isEqual:@1]) {
            // 支付宝: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:responseJson[@"data"] fromScheme:kUrlScheme callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    
                    NXSignatureController * secondVC = [[NXSignatureController alloc]init];
                    secondVC.signatureVCBlock = ^(UIImage *signatureImage) {
                        [[ToolNet sharedManager] uploadSingImage:signatureImage userCode:self.userCode paraentVC:self completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                            NSLog(@"response:%@",responseObject);
                            if ([responseObject[@"code"] isEqual:@1]) {
                                AuditViewController *auditVC = [[AuditViewController alloc] init];
                                [self.navigationController pushViewController:auditVC animated:YES];
                            }else
                            {
                                [self showMessage:responseJson[@"msg"]];
                            }
                        }];
                    };
                    [self presentViewController:secondVC animated:YES completion:nil];
                }
                else {
                    [self showMessage:@"支付失败"];
                }
            }];
        }
        else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self showMessage:responseJson[@"msg"]];
            });
        }
    }];
}

- (void)showAlertWait
{
    mAlert = [UIAlertController alertControllerWithTitle:@"正在获取支付凭据,请稍后..." message:nil preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:mAlert animated:YES completion:nil];
}

- (void)hideAlert
{
    if (mAlert != nil)
    {
        [mAlert dismissViewControllerAnimated:YES completion:nil];
        mAlert = nil;
    }
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    
    NSArray *titleArr = @[@"支付宝支付"];
    NSArray * imageArr = @[@"alipay"];
    cell.textLabel.text = titleArr[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:imageArr[indexPath.row]];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor =  [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [cell.contentView addSubview:line];
    line.sd_layout
    .bottomSpaceToView(cell.contentView, 0)
    .leftSpaceToView(cell.contentView, 0)
    .widthIs(kScreenWidth)
    .heightIs(1);
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
